import React, { useState, useEffect } from 'react';
import { Card, Table, Tag, Button, Modal, Descriptions, message, Spin, Empty } from 'antd';
import { EyeOutlined, ReloadOutlined, CheckOutlined } from '@ant-design/icons';
import styles from './OrderManagement.module.css';

const OrderManagement = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState(null);

  // 获取订单列表
  const fetchOrders = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        message.error('用户未登录，请先登录');
        return;
      }

      const response = await fetch('http://localhost:3001/api/orders', {
        headers: {
          'Authorization': token.startsWith('Bearer ') ? token : `Bearer ${token}`
        }
      });

      if (!response.ok) {
        throw new Error('获取订单失败');
      }

      const data = await response.json();
      if (data.success) {
        setOrders(data.data || []);
      } else {
        message.error(data.message || '获取订单失败');
      }
    } catch (error) {
      console.error('获取订单失败:', error);
      message.error('获取订单失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 获取订单详情
  const fetchOrderDetail = async (orderId) => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        message.error('用户未登录，请先登录');
        return;
      }

      const response = await fetch(`http://localhost:3001/api/order/${orderId}`, {
        headers: {
          'Authorization': token.startsWith('Bearer ') ? token : `Bearer ${token}`
        }
      });

      if (!response.ok) {
        throw new Error('获取订单详情失败');
      }

      const data = await response.json();
      if (data.success) {
        setSelectedOrder(data.data);
        setDetailModalVisible(true);
      } else {
        message.error(data.message || '获取订单详情失败');
      }
    } catch (error) {
      console.error('获取订单详情失败:', error);
      message.error('获取订单详情失败，请稍后重试');
    }
  };

  // 手动更新订单状态为已支付（用于测试）
  const updateOrderStatus = async (orderId) => {
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        message.error('用户未登录，请先登录');
        return;
      }

      const response = await fetch(`http://localhost:3001/api/order/${orderId}/status`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': token.startsWith('Bearer ') ? token : `Bearer ${token}`
        },
        body: JSON.stringify({ status: '已支付' })
      });

      if (!response.ok) {
        throw new Error('更新订单状态失败');
      }

      const data = await response.json();
      if (data.success) {
        message.success('订单状态已更新为已支付');
        fetchOrders(); // 刷新订单列表
      } else {
        message.error(data.message || '更新订单状态失败');
      }
    } catch (error) {
      console.error('更新订单状态失败:', error);
      message.error('更新订单状态失败，请稍后重试');
    }
  };

  // 显示订单状态标签
  const getStatusTag = (status) => {
    const statusConfig = {
      'pending': { color: 'orange', text: '待支付' },
      '已支付': { color: 'green', text: '已支付' },
      'cancelled': { color: 'red', text: '已取消' },
      'refunded': { color: 'blue', text: '已退款' }
    };

    const config = statusConfig[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 表格列配置
  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 120,
    },
    {
      title: '用户昵称',
      dataIndex: 'userNickname',
      key: 'userNickname',
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      width: 100,
      render: (amount) => `¥${amount}`,
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      width: 100,
      render: (status) => getStatusTag(status),
    },
    {
      title: '提交时间',
      dataIndex: 'submitTime',
      key: 'submitTime',
      width: 160,
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      key: 'payTime',
      width: 160,
      render: (time) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <div style={{ display: 'flex', gap: '8px' }}>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => fetchOrderDetail(record.orderId)}
          >
            查看详情
          </Button>
          {record.orderStatus === 'pending' && (
            <Button
              type="link"
              icon={<CheckOutlined />}
              onClick={() => updateOrderStatus(record.orderId)}
              style={{ color: '#52c41a' }}
            >
              标记已支付
            </Button>
          )}
        </div>
      ),
    },
  ];

  useEffect(() => {
    fetchOrders();
  }, []);

  return (
    <div className={styles.orderManagement}>
      <Card
        title="订单管理"
        extra={
          <Button
            type="primary"
            icon={<ReloadOutlined />}
            onClick={fetchOrders}
            loading={loading}
          >
            刷新
          </Button>
        }
      >
        {loading ? (
          <div className={styles.loadingContainer}>
            <Spin size="large" />
            <p>加载中...</p>
          </div>
        ) : orders.length === 0 ? (
          <Empty
            description="暂无订单数据"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          <Table
            columns={columns}
            dataSource={orders}
            rowKey="orderId"
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total, range) =>
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            }}
            scroll={{ x: 1200 }}
          />
        )}
      </Card>

      {/* 订单详情弹窗 */}
      <Modal
        title="订单详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedOrder && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="订单号" span={2}>
              {selectedOrder.orderId}
            </Descriptions.Item>
            <Descriptions.Item label="用户昵称">
              {selectedOrder.userNickname}
            </Descriptions.Item>
            <Descriptions.Item label="手机号">
              {selectedOrder.phone}
            </Descriptions.Item>
            <Descriptions.Item label="商品名称" span={2}>
              {selectedOrder.productName}
            </Descriptions.Item>
            <Descriptions.Item label="商品类型">
              {selectedOrder.productType === 'book' ? '图书' : selectedOrder.productType}
            </Descriptions.Item>
            <Descriptions.Item label="订单金额">
              ¥{selectedOrder.orderAmount}
            </Descriptions.Item>
            <Descriptions.Item label="订单状态" span={2}>
              {getStatusTag(selectedOrder.orderStatus)}
            </Descriptions.Item>
            <Descriptions.Item label="提交时间" span={2}>
              {new Date(selectedOrder.submitTime).toLocaleString()}
            </Descriptions.Item>
            {selectedOrder.payTime && (
              <Descriptions.Item label="支付时间" span={2}>
                {new Date(selectedOrder.payTime).toLocaleString()}
              </Descriptions.Item>
            )}
            {selectedOrder.alipayTradeNo && (
              <Descriptions.Item label="支付宝交易号" span={2}>
                {selectedOrder.alipayTradeNo}
              </Descriptions.Item>
            )}
            {selectedOrder.remark && (
              <Descriptions.Item label="备注" span={2}>
                {selectedOrder.remark}
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default OrderManagement;
